package com.coai.ai.service

import com.coai.ai.client.OpenAIClient
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import org.springframework.stereotype.Service

/**
 * 智能客服助手
 */
@Service
class SmartCustomerService(
    private val openAIClient: OpenAIClient
) {
    
    /**
     * 处理客户查询
     */
    suspend fun handleCustomerQuery(
        customerId: String,
        query: String,
        conversationHistory: List<ChatMessage>
    ): CustomerServiceResponse {
        
        // 构建上下文
        val context = buildContext(conversationHistory)
        
        // 意图识别
        val intent = classifyIntent(query)
        
        // 情绪分析
        val emotion = analyzeEmotion(query)
        
        // 根据意图生成回复
        val response = when (intent.type) {
            IntentType.ORDER_INQUIRY -> handleOrderInquiry(customerId, query, context)
            IntentType.PRODUCT_SEARCH -> handleProductSearch(query)
            IntentType.COMPLAINT -> handleComplaint(customerId, query, emotion)
            else -> handleGeneralQuery(query, context)
        }
        
        return response
    }
    
    /**
     * 意图分类
     */
    private suspend fun classifyIntent(query: String): Intent {
        val prompt = """
            分析以下用户查询的意图，返回JSON格式：
            {"type": "意图类型", "confidence": 置信度}
            
            意图类型包括：ORDER_INQUIRY(订单查询), PRODUCT_SEARCH(商品搜索), 
            COMPLAINT(投诉), REFUND_REQUEST(退款), GENERAL_QUESTION(一般问题)
            
            用户查询：$query
        """.trimIndent()
        
        val response = openAIClient.chat(prompt, temperature = 0.3)
        return parseIntent(response)
    }
    
    /**
     * 情绪分析
     */
    private suspend fun analyzeEmotion(text: String): EmotionAnalysis {
        val prompt = """
            分析以下文本的情绪，返回JSON格式：
            {"sentiment": "情感倾向", "intensity": 强度0-1, "emotions": {"情绪": 分数}}
            
            情感倾向：POSITIVE, NEUTRAL, NEGATIVE
            
            文本：$text
        """.trimIndent()
        
        val response = openAIClient.chat(prompt, temperature = 0.3)
        return parseEmotion(response)
    }
    
    /**
     * 处理订单查询
     */
    private suspend fun handleOrderInquiry(
        customerId: String,
        query: String,
        context: String
    ): CustomerServiceResponse {
        // 这里可以调用订单服务获取实际订单数据
        val orderData = getCustomerOrders(customerId)
        
        val prompt = """
            作为客服助手，根据以下信息回答客户问题：
            
            客户问题：$query
            
            订单信息：$orderData
            
            对话历史：$context
            
            请提供专业、友好的回答。
        """.trimIndent()
        
        val answer = openAIClient.chat(prompt)
        
        return CustomerServiceResponse(
            type = ResponseType.ANSWER,
            message = answer
        )
    }
    
    /**
     * 处理商品搜索
     */
    private suspend fun handleProductSearch(query: String): CustomerServiceResponse {
        // 调用商品搜索服务
        val products = searchProducts(query)
        
        val prompt = """
            为以下商品生成推荐语：
            
            商品列表：${products.joinToString("\n")}
            
            用户搜索：$query
            
            生成吸引人的商品介绍。
        """.trimIndent()
        
        val introduction = openAIClient.chat(prompt)
        
        return CustomerServiceResponse(
            type = ResponseType.PRODUCT_LIST,
            message = introduction,
            products = products
        )
    }
    
    /**
     * 处理投诉
     */
    private suspend fun handleComplaint(
        customerId: String,
        query: String,
        emotion: EmotionAnalysis
    ): CustomerServiceResponse {
        // 创建工单
        val ticket = createTicket(customerId, query, emotion)
        
        val prompt = """
            作为客服，对以下投诉给出专业、同理心的回复：
            
            投诉内容：$query
            
            情绪分析：情感=${emotion.sentiment}, 强度=${emotion.intensity}
            
            要求：
            1. 表达理解和歉意
            2. 说明已创建工单
            3. 提供解决方案或时间线
            4. 语气要诚恳
        """.trimIndent()
        
        val response = openAIClient.chat(prompt)
        
        return CustomerServiceResponse(
            type = ResponseType.TICKET_CREATED,
            message = response,
            structuredData = mapOf("ticketId" to ticket.id)
        )
    }
    
    /**
     * 处理一般查询
     */
    private suspend fun handleGeneralQuery(
        query: String,
        context: String
    ): CustomerServiceResponse {
        val prompt = """
            作为专业客服，回答以下问题：
            
            问题：$query
            
            对话历史：$context
            
            提供准确、友好的回答。
        """.trimIndent()
        
        val answer = openAIClient.chat(prompt)
        
        return CustomerServiceResponse(
            type = ResponseType.ANSWER,
            message = answer
        )
    }
    
    // 辅助方法（实际实现需要调用相应服务）
    private fun buildContext(history: List<ChatMessage>): String {
        return history.joinToString("\n") { "${it.role}: ${it.content}" }
    }
    
    private fun getCustomerOrders(customerId: String): String {
        // 调用订单服务（模拟实现）
        return try {
            // TODO: 实际集成时调用订单服务 REST API
            // val orders = restTemplate.getForObject(
            //     "http://order-service/api/orders?customerId=$customerId",
            //     OrderList::class.java
            // )
            """
            订单信息：
            - 订单号：ORD-2024-001, 状态：配送中
            - 订单号：ORD-2024-002, 状态：已完成
            """.trimIndent()
        } catch (e: Exception) {
            logger.error("Failed to get customer orders", e)
            "暂无订单信息"
        }
    }
    
    private fun searchProducts(query: String): List<Product> {
        // 调用商品搜索服务（模拟实现）
        return try {
            // TODO: 实际集成时调用商品服务 REST API
            // val products = restTemplate.getForObject(
            //     "http://product-service/api/products/search?q=$query",
            //     ProductList::class.java
            // )
            
            // 模拟返回搜索结果
            listOf(
                Product("prod-001", "相关商品A"),
                Product("prod-002", "相关商品B")
            )
        } catch (e: Exception) {
            logger.error("Failed to search products", e)
            emptyList()
        }
    }
    
    private fun createTicket(customerId: String, content: String, emotion: EmotionAnalysis): Ticket {
        // 调用工单服务（模拟实现）
        return try {
            // TODO: 实际集成时调用工单服务 REST API
            // val ticket = restTemplate.postForObject(
            //     "http://ticket-service/api/tickets",
            //     TicketRequest(customerId, content, emotion.sentiment.name),
            //     Ticket::class.java
            // )
            
            val ticketId = "TKT-${System.currentTimeMillis()}"
            logger.info("Created ticket $ticketId for customer $customerId")
            Ticket(ticketId)
        } catch (e: Exception) {
            logger.error("Failed to create ticket", e)
            Ticket("TKT-ERROR")
        }
    }
    
    private fun parseIntent(json: String): Intent {
        // JSON解析
        return try {
            val typeMatch = Regex(""""type"\s*:\s*"([^"]+)"""").find(json)
            val confidenceMatch = Regex(""""confidence"\s*:\s*(\d+\.?\d*)""").find(json)
            
            val typeStr = typeMatch?.groupValues?.get(1) ?: "GENERAL_QUESTION"
            val confidence = confidenceMatch?.groupValues?.get(1)?.toDoubleOrNull() ?: 0.9
            
            val intentType = when {
                typeStr.contains("ORDER", ignoreCase = true) -> IntentType.ORDER_INQUIRY
                typeStr.contains("PRODUCT", ignoreCase = true) -> IntentType.PRODUCT_SEARCH
                typeStr.contains("COMPLAINT", ignoreCase = true) -> IntentType.COMPLAINT
                typeStr.contains("REFUND", ignoreCase = true) -> IntentType.REFUND_REQUEST
                else -> IntentType.GENERAL_QUESTION
            }
            
            Intent(intentType, confidence)
        } catch (e: Exception) {
            logger.error("Failed to parse intent", e)
            Intent(IntentType.GENERAL_QUESTION, 0.9)
        }
    }
    
    private fun parseEmotion(json: String): EmotionAnalysis {
        // JSON解析
        return try {
            val sentimentMatch = Regex(""""sentiment"\s*:\s*"([^"]+)"""").find(json)
            val intensityMatch = Regex(""""intensity"\s*:\s*(\d+\.?\d*)""").find(json)
            
            val sentimentStr = sentimentMatch?.groupValues?.get(1) ?: "NEUTRAL"
            val intensity = intensityMatch?.groupValues?.get(1)?.toDoubleOrNull() ?: 0.5
            
            val sentiment = when {
                sentimentStr.contains("POSITIVE", ignoreCase = true) -> Sentiment.POSITIVE
                sentimentStr.contains("NEGATIVE", ignoreCase = true) -> Sentiment.NEGATIVE
                else -> Sentiment.NEUTRAL
            }
            
            // 提取情绪标签
            val emotions = mutableMapOf<String, Double>()
            val emotionsMatch = Regex(""""emotions"\s*:\s*\{([^}]+)\}""").find(json)
            if (emotionsMatch != null) {
                val emotionsStr = emotionsMatch.groupValues[1]
                Regex(""""([^"]+)"\s*:\s*(\d+\.?\d*)""").findAll(emotionsStr).forEach { match ->
                    val emotion = match.groupValues[1]
                    val value = match.groupValues[2].toDoubleOrNull() ?: 0.0
                    emotions[emotion] = value
                }
            }
            
            EmotionAnalysis(sentiment, intensity, emotions)
        } catch (e: Exception) {
            logger.error("Failed to parse emotion", e)
            EmotionAnalysis(Sentiment.NEUTRAL, 0.5, emptyMap())
        }
    }
}

// 数据类
data class ChatMessage(
    val role: String,
    val content: String
)

data class CustomerServiceResponse(
    val type: ResponseType,
    val message: String,
    val products: List<Product> = emptyList(),
    val structuredData: Map<String, Any> = emptyMap()
)

enum class ResponseType {
    ANSWER, PRODUCT_LIST, TICKET_CREATED, TRANSFER_TO_HUMAN
}

data class Intent(
    val type: IntentType,
    val confidence: Double
)

enum class IntentType {
    ORDER_INQUIRY, PRODUCT_SEARCH, COMPLAINT, REFUND_REQUEST, GENERAL_QUESTION
}

data class EmotionAnalysis(
    val sentiment: Sentiment,
    val intensity: Double,
    val emotions: Map<String, Double>
)

enum class Sentiment {
    POSITIVE, NEUTRAL, NEGATIVE
}

data class Product(
    val id: String,
    val name: String
)

data class Ticket(
    val id: String
)
